﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using NoteSystem.Utils;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Security.Principal;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection.Emit;

namespace NoteSystem
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["User"]!=null)
                {
                    InitUserNote();
                }
            }
           
        }
        #region 日志加载
        public void InitUserNote()
        {
            DataSet ds = DbHelper.Query("select u.account,n.* from users u inner join notes n on u.id=n.user_id ");
            //把容器给Repeater
            rptUserNotes.DataSource= ds;
            rptUserNotes.DataBind();
        }
        #endregion
        //静态页拼接
        public string InitUser()
        {
            if (Session["User"]==null)
                return "";
            DataRow userRow = (DataRow)Session["User"];
            string genderText = userRow["gender"].ToString()=="0" ? "男" : "女";
            string city = userRow["CityName"].ToString();
            string url = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=59818651&appsecret=U1v8ifrw&city="+city.Replace("市"," ");
            WebClient client = new WebClient();//实例化一个远程访问类
            byte[] btResult = client.DownloadData(url);//使用访问类请求接口，并将接口内容解析为字符串
            string result = Encoding.UTF8.GetString(btResult);//JSON
            //借用第三方序列反序列化库Newtonsoft
            JObject obj = (JObject)JsonConvert.DeserializeObject(result);
            //将json字符串反序列化成newtonsoft提供的一个对象
            //登录人信息
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<div class=\"segment left\">");
            stringBuilder.Append("<i class=\" glyphicon glyphicon-user left\" ></i>");
            stringBuilder.Append($"<h3 class=\"left\">欢迎{userRow["account"]}登录<br>");
            stringBuilder.Append("<span>管理这个设备及其传感器</span>");
            stringBuilder.Append("</h3>");
            stringBuilder.Append("</div>");
            stringBuilder.Append("<div class=\"clear\"></div>");
            stringBuilder.Append("<div class=\"segment2\">");
            stringBuilder.Append("<div class=\"user_left\">");
            stringBuilder.Append($"<img widtb=\"160\" height=\"160\" src=\"{userRow["img_url"]}\">");
            stringBuilder.Append("</div>");
            stringBuilder.Append("<div class=\"user_right\">");
            stringBuilder.Append($"<h5>你好：{userRow["account"]}<br>");
            stringBuilder.Append($" <span><i  class=\"glyphicon glyphicon-time\"></i>{DateTime.Now}</span>");
            stringBuilder.Append(" </h5>");
            stringBuilder.Append($" <p>所在地:{userRow["CityName"]}<br>");
            stringBuilder.Append($"性别:{genderText}<br>");
            stringBuilder.Append($"QQ:{userRow["qq"]}<br>");
            stringBuilder.Append($"邮箱：{userRow["email"]}");
            stringBuilder.Append(" </p>");
            stringBuilder.Append($" <p>天气：{obj["wea"]}  最高温度:{obj["tem1"]} 最低温度:{obj["tem2"]} </p>");
            stringBuilder.Append("</div>");
            stringBuilder.Append(" </civ>");
            return stringBuilder.ToString();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            #region 全选删除
            int sign = 0;
            //遍历所有的数据行
            for (int i = 0; i < rptUserNotes.Items.Count; i++)
            {
                //获取每一行的勾选框
                CheckBox cbx = rptUserNotes.Items[i].FindControl("cbxItem") as CheckBox;
                int noteId = Convert.ToInt32((rptUserNotes.Items[i].FindControl("hfNoteId") as HiddenField).Value);
                //判断勾选框是否勾选
                if (cbx.Checked == true)
                {
                    int flag = DbHelper.ExecuteSql("delete from notes where id=" + noteId);
                    if (flag > 0)
                    {
                        sign++;
                    }
                }
            }
            if (sign > 0)
                Response.Write($"<script>alert('删除成功，共删除{sign}条')</script>");
            InitUserNote();

            #endregion
        }

        protected void rptUserNotes_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int user_id = Convert.ToInt32((e.Item.FindControl("hfUserId") as HiddenField).Value);
            DataRow userRow = (DataRow)Session["User"];
            int login_id = Convert.ToInt32(userRow["id"]);
            int manager = Convert.ToInt32(userRow["manager"]);
            if (login_id != user_id && manager !=1)
            {
                e.Item.FindControl("lbtnUpdate").Visible=false;
                e.Item.FindControl("lbtnDelete").Visible=false;
                e.Item.FindControl("cbxItem").Visible = false;

            }
      
        }
        protected void rptUserNotes_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int note_id = Convert.ToInt32(e.CommandArgument);
            if (e.CommandName=="Delete")
            {
                int flag = DbHelper.ExecuteSql($"delete from notes where id={note_id}");
                if (flag>0)
                {
                    Response.Write("<script>alert('删除成功')</script>");
                    InitUserNote();
                }
            }
            else
            {
                Response.Redirect("Note.aspx?id="+note_id);
            }
        }
    }
}